<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/6/16
 * Time: 16:23
 */

namespace app\manage\model;


use think\Db;

class User
{
    /**
     *用户登录验证
     */
    public function doLogin($data){
        $pass=$data['password'];
        $user = Db::name('user')
            ->where(['user_login'=>$data['account']])
            ->find();
        if(!empty($user)){
            if (cmf_compare_password($pass, $user['user_pass'])) {
                $groups = Db::name('RoleUser')
                    ->alias("a")
                    ->join('__ROLE__ b', 'a.role_id =b.r_id')
                    ->where(["b.user_id" => $user["u_id"], "b.status" => 1])
                    ->value("role_id");
                if ($user["u_id"] != 1 && (empty($groups) || empty($user['user_status']))) {
                    returnJson(-2004,'该用户已被禁用, 请联系管理');
                }
                //获取用户登陆ip和时间
                $result['ip']   = get_client_ip(0, true);
                $result['create_time'] = time();
                $result['user_id'] = $user['u_id'];
                $result['note'] = '登录';

                Db::name('user_log')->insert($result);

                Db::name('user')->where('u_id',$user['u_id'])->setInc('login_times',1);

                return $user['u_id'];
            }else{
                returnJson(-2004,'密码错误');
            }

        }else{
            returnJson(-2004,'用户不存在');
        }


    }

    /**
     * 查看后台用户头像和昵称
     */
    public function selectOne($user_id){
        $user = Db::name('user')
            ->where(['u_id'=>$user_id])
            ->find();
        return $user;
    }
    /**
     * 用户管理-会员列表
     */
    public function userList($filter,$page,$page_size){
        $where=[];
        //城市
        $city = empty($filter['city']) ? '' : $filter['city'];
        if(!empty($city)){
            $where['mi.address'] = ['like', "%".$city."%"];
        }

        //查询传入时间当天的数据  0-24点
        $endTime = empty($filter['end_time']) ? 0 : strtotime($filter['end_time']);
        $start=strtotime('0:0:0',$endTime);
        $end=strtotime('24:00:00',$endTime);

        if (!empty($endTime)) {
            $where['m.create_time'] = [['>= time', $start], ['<= time', $end]];
        }
       /* $startTime = empty($filter['start_time']) ? 0 : strtotime($filter['start_time']);
        $endTime = empty($filter['end_time']) ? 0 : strtotime($filter['end_time']);
        if (!empty($startTime) && !empty($endTime)) {
            $where['m.create_time'] = [['>= time', $startTime], ['<= time', $endTime]];
        } else {
            if (!empty($startTime)) {
                $where['m.create_time'] = ['>= time', $startTime];
            }
            if (!empty($endTime)) {
                $where['m.create_time'] = ['<= time', $endTime];
            }
        }*/
        //会员到期日期
        $endTime2 = empty($filter['expire_end_time']) ? 0 : strtotime($filter['expire_end_time']);
        $start2=strtotime('0:0:0',$endTime2);
        $end2=strtotime('24:00:00',$endTime2);
        if (!empty($endTime2)) {
            $where['mg.end_time'] = [['>= time', $start2], ['<= time', $end2]];
        }

       /* $startTime2 = empty($filter['expire_start_time']) ? 0 : strtotime($filter['expire_start_time']);
        $endTime2 = empty($filter['expire_end_time']) ? 0 : strtotime($filter['expire_end_time']);
        if (!empty($startTime2) && !empty($endTime2)) {
            $where['mg.end_time'] = [['>= time', $startTime2], ['<= time', $endTime2]];
        } else {
            if (!empty($startTime2)) {
                $where['mg.end_time'] = ['>= time', $startTime2];
            }
            if (!empty($endTime2)) {
                $where['mg.end_time'] = ['<= time', $endTime2];
            }
        }*/

        //会员等级  1=普卡  2=银卡  3=金卡  4=钻卡
        if(!empty($filter['grade_type'])){
            $where['mg.grade_type'] = $filter['grade_type'];
        }
        //关键词搜索
        $keyword = empty($filter['keyword']) ? '' : $filter['keyword'];
        if(!empty($keyword)){
//            $where['m.nickName|m.mobile'] = ['like', "%".$keyword."%"];
            $where['m.mobile'] = ['like', "%".$keyword."%"];
        }

        //member_asset  member_grade 出现重复数据 需要去重

        $field='m.member_id,m.nickName,m.mobile,m.create_time,mi.address,mi.status,ma.score,ma.coin,ma.frozen_score,
            mg.end_time,mg.grade_type';
        $data=Db::name('member')->alias('m')
            ->field($field)
            ->join('member_info mi','mi.member_id=m.member_id','left')
            ->join('member_asset ma','ma.member_id=m.member_id','left')
            ->join('member_grade mg','mg.member_id=m.member_id','left')
            ->where("ma.asset_id in (select max(asset_id) from  mm_member_asset group by member_id)")
            ->where("mg.grade_id in (select max(grade_id) from  mm_member_grade group by member_id)")
            ->where($where)
            ->page($page,$page_size)
            ->select();
        //dump(Db::name('member')->getLastSql());
        if(!empty($data)){
            foreach ($data as $k=>&$v){
                //序号
                //$v['id']=$k+1;
                //是否实名认证
                if(!isset($v['status']) || empty($v['status'])){
                    $v['status']=0;
                }
                if(!isset($v['address']) || empty($v['address'])){
                    $v['address']='';
                }
                if(!isset($v['end_time']) || empty($v['end_time'])){
                    $v['end_time']=0;
                }
                if(!isset($v['grade_type']) || empty($v['grade_type'])){
                    $v['grade_type']=1;
                }

            }
        }

        $total_num=Db::name('member')->alias('m')
            ->join('member_info mi','mi.member_id=m.member_id','left')
            ->join('member_asset ma','ma.member_id=m.member_id','left')
            ->join('member_grade mg','mg.member_id=m.member_id','left')
            ->where("ma.asset_id in (select max(asset_id) from  mm_member_asset group by member_id)")
            ->where("mg.grade_id in (select max(grade_id) from  mm_member_grade group by member_id)")
            ->where($where)
            ->count();
        $t_page=ceil($total_num / $page_size);

        $list['current_page'] = $page;
        $list['total_page'] =$t_page;
        $list['page_num'] = $page_size;
        $list['total_num'] = $total_num;
        $list['data'] = $data;

        return $list;
    }

    /**
     * 用户管理-会员详情
     */
    public function userDetail($member_id){
        $field='m.nickName,m.avatarUrl,m.gender,m.mobile,mi.real_name,mi.card,mi.company,mi.com_post,mi.industry,
        ma.coin,ma.score,ma.frozen_score,m.create_time,mi.wx_account,mi.qq_account,mi.landline';
        $data=Db::name('member')->alias('m')
            ->field($field)
            ->join('member_info mi','mi.member_id=m.member_id','left')
            ->join('member_asset ma','ma.member_id=m.member_id','left')
            ->where('m.member_id',$member_id)
            ->find();

        if(!isset($data['real_name']) || empty($data['real_name'])){
            $data['real_name']='';
        }
        if(!isset($data['card']) || empty($data['card'])){
            $data['card']='';
        }
        if(!isset($data['company']) || empty($data['company'])){
            $data['company']='';
        }
        if(!isset($data['com_post']) || empty($data['com_post'])){
            $data['com_post']='';
        }
        if(!isset($data['industry']) || empty($data['industry'])){
            $data['industry']='';
        }


        return $data;
    }

    /**
     * 用户管理-修改会员等级，积分-页面   type  1=修改等级  2=修改积分
     */
    public function editUserLevel($member_id,$type){

        if($type==1){
            $data=Db::name('member')->alias('m')
                ->field('m.member_id,m.mobile,mg.grade_type,mg.end_time')
                ->join('member_grade mg','mg.member_id=m.member_id','left')
                ->where('m.member_id',$member_id)
                ->find();
        }else{
            $data=Db::name('member')->alias('m')
                ->field('m.member_id,m.mobile,ma.score')
                ->join('member_asset ma','ma.member_id=m.member_id','left')
                ->where('m.member_id',$member_id)
                ->find();
        }


        return $data;
    }

    /**
     * 用户管理-修改会员等级，积分-提交 type  1=修改等级  2=修改积分
     */
    public function editUserPost($param,$type){

        if($type==1){
            $end_time=strtotime($param['end_time']);
            Db::name('member_grade')
                ->where('member_id',$param['member_id'])
                ->update(['grade_type'=>$param['grade_type'],'end_time'=>$end_time]);
        }else{
            Db::name('member_asset')
                ->where('member_id',$param['member_id'])
                ->update(['score'=>$param['score'],'update_time'=>time()]);
        }
    }


    /**
     * 查询用户 --人脉名片的地址
     */
    public function selectUserAddress(){
        $data=Db::name('member')->alias('m')
            ->distinct('mi.address')
            ->field('mi.address')
            ->join('member_info mi','mi.member_id=m.member_id')
            ->where(['mi.address'=>['neq','']])
            ->select();
        return $data;

    }

    /**
     * 会员升级消耗积分记录--列表
     */
    public function scoreList($filter,$page,$page_size){
        $where=[];
        //城市
        $city = empty($filter['city']) ? '' : $filter['city'];
        if(!empty($city)){
            $where['mi.address'] = ['like', "%".$city."%"];
        }

        //会员等级  1=普卡  2=银卡  3=金卡  4=钻卡
        if(!empty($filter['grade_type'])){
            $where['mgo.grade_type'] = $filter['grade_type'];
        }
        //关键词搜索
        $keyword = empty($filter['keyword']) ? '' : $filter['keyword'];
        if(!empty($keyword)){
            $where['m.nickName|m.mobile'] = ['like', "%".$keyword."%"];
        }

        $field='m.mobile,m.nickName,mgo.gradeID,mgo.grade_type,mgo.create_time,mgo.amount,mi.address';
        $data=Db::name('member_grade_order')->alias('mgo')
            ->field($field)
            ->join('member m','m.member_id=mgo.member_id')
            ->join('member_info mi','mi.member_id=mgo.member_id','left')
            ->where($where)
            ->where(['mgo.status'=>1])
            ->page($page,$page_size)
            ->select();

        if(!empty($data)){
            foreach ($data as $k=>&$v){
                if(!isset($v['address']) || empty($v['address'])){
                    $v['address']='';
                }
            }
        }

        $total_num=Db::name('member_grade_order')->alias('mgo')
            ->join('member m','m.member_id=mgo.member_id')
            ->join('member_info mi','mi.member_id=mgo.member_id','left')
            ->where(['mgo.status'=>1])
            ->where($where)
            ->count();
        $t_page=ceil($total_num / $page_size);

        //升级消耗总积分
        $count_money=Db::name('member_grade_order')->alias('mgo')
            ->join('member m','m.member_id=mgo.member_id')
            ->join('member_info mi','mi.member_id=mgo.member_id','left')
            ->where(['mgo.status'=>1])
            ->where($where)
            ->sum('mgo.amount');

        $list['current_page'] = $page;
        $list['total_page'] =$t_page;
        $list['page_num'] = $page_size;
        $list['total_num'] = $total_num;
        $list['count_money'] = $count_money;
        $list['data'] = $data;

        return $list;
    }

    /**
     * 转账记录--列表
     */
    public function transferList($filter,$page,$page_size){
        $where=[];

        //查询传入时间当天的数据  0-24点
        $endTime = empty($filter['end_time']) ? 0 : strtotime($filter['end_time']);
        $start=strtotime('0:0:0',$endTime);
        $end=strtotime('24:00:00',$endTime);

        if (!empty($endTime)) {
            $where['mt.create_time'] = [['>= time', $start], ['<= time', $end]];
        }
        //转账类型 1 直接转账 2 担保转账
        if(!empty($filter['trans_type'])){
            $where['mt.trans_type'] = $filter['trans_type'];
        }
        //关键词搜索
        $keyword = empty($filter['keyword']) ? '' : $filter['keyword'];
        if(!empty($keyword)){
            $where['m.nickName|m.mobile'] = ['like', "%".$keyword."%"];
        }

        $field='m.mobile,m.nickName,mt.trans_id,mt.trans_type,mt.create_time,mt.transfer_num,mt.receive_mobile';
        $data=Db::name('member_transfer')->alias('mt')
            ->field($field)
            ->join('member m','m.member_id=mt.member_id')
            ->where($where)
            ->where(['mt.status'=>2])
            ->page($page,$page_size)
            ->select();

        $total_num=Db::name('member_transfer')->alias('mt')
            ->join('member m','m.member_id=mt.member_id')
            ->where(['mt.status'=>2])
            ->where($where)
            ->count();
        $t_page=ceil($total_num / $page_size);

        //转账总积分
        $count_money=Db::name('member_transfer')->alias('mt')
            ->join('member m','m.member_id=mt.member_id')
            ->where(['mt.status'=>2])
            ->where($where)
            ->sum('mt.transfer_num');

        $list['current_page'] = $page;
        $list['total_page'] =$t_page;
        $list['page_num'] = $page_size;
        $list['total_num'] = $total_num;
        $list['count_money'] = $count_money;
        $list['data'] = $data;

        return $list;
    }

    /**
     * 推荐关系
     */
    public function relation($page,$page_size){

        $data=Db::name('member')
            ->field('member_id,mobile,nickName,create_time')
            //->where(['uid_1'=>0])
            ->page($page,$page_size)
            ->select();

        foreach ($data as $k=>&$v){
            //推荐人数
            $count=Db::name('member')->where('uid_1',$v['member_id'])
                ->count();
            $v['count']=$count;
        }


        $total_num=Db::name('member')
            //->where(['uid_1'=>0])
            ->count();

        $t_page=ceil($total_num / $page_size);

        $list['current_page'] = $page;
        $list['total_page'] =$t_page;
        $list['page_num'] = $page_size;
        $list['total_num'] = $total_num;
        $list['data'] = $data;

        return $list;
    }

    /**
     * 查询下级关系,分页
     */
    public function lowerShip($member_id,$page,$page_size){
        $data=Db::name('member')
            ->field('member_id,mobile,nickName,create_time')
            ->where(['uid_1'=>$member_id])
            ->page($page,$page_size)
            ->select();

        foreach ($data as $k=>&$v){
            //推荐人数
            $count=Db::name('member')->where('uid_1',$v['member_id'])
                ->count();
            $v['count']=$count;
        }

        $total_num=Db::name('member')
            ->where(['uid_1'=>$member_id])
            ->count();

        $t_page=ceil($total_num / $page_size);

        $list['current_page'] = $page;
        $list['total_page'] =$t_page;
        $list['page_num'] = $page_size;
        $list['total_num'] = $total_num;
        $list['data'] = $data;

        return $list;
    }

    /**
     * 会员推荐关系   ----递归，无分页----------
     */
    public function relationship($pid = 0, &$lists = array(), $deep = 1){
        $data=Db::name('member')
            ->field('member_id,mobile,nickName,create_time')
            ->where(['uid_1'=>$pid])
            ->select();

        foreach ($data as $k=>&$v){

            $child=$this->relationship($v['member_id'], $data, ++$deep);
            $v['child']=$child;
        }

        return $data;
    }

    /**
     * 推客列表
     */
    public function  twitterList($filter,$page,$page_size){
        $where=[];
        $where['ai.status']=['in',[1,3]];
        $where['ai.is_delete']=1;
        //dump($where);

        //查询传入时间当天的数据  0-24点
        $endTime = empty($filter['end_time']) ? 0 : strtotime($filter['end_time']);
        $start=strtotime('0:0:0',$endTime);
        $end=strtotime('24:00:00',$endTime);

        if (!empty($endTime)) {
            $where['ai.create_time'] = [['>= time', $start], ['<= time', $end]];
        }

        /* $startTime = empty($filter['start_time']) ? 0 : strtotime($filter['start_time']);
         $endTime = empty($filter['end_time']) ? 0 : strtotime($filter['end_time']);
         if (!empty($startTime) && !empty($endTime)) {
             $where['create_time'] = [['>= time', $startTime], ['<= time', $endTime]];
         } else {
             if (!empty($startTime)) {
                 $where['create_time'] = ['>= time', $startTime];
             }
             if (!empty($endTime)) {
                 $where['create_time'] = ['<= time', $endTime];
             }
         }*/

        $keyword = empty($filter['keyword']) ? '' : $filter['keyword'];
        if(!empty($keyword)){
            $where['m.mobile'] = ['like', "%".$keyword."%"];
        }


        $field='ai.ai_id as t_id,m.mobile as phone,ai.create_time,ai.status,m.nickName';
        $data=Db::name('attract_invest')->alias('ai')
            ->field($field)
            ->join('member m','m.member_id=ai.member_id')
            ->where($where)
            ->page($page,$page_size)
            ->select();

        $total_num=Db::name('attract_invest')->alias('ai')
            ->join('member m','m.member_id=ai.member_id')
            ->where($where)
            ->count();
        $t_page=ceil($total_num / $page_size);

        $list['current_page'] = $page;
        $list['total_page'] =$t_page;
        $list['page_num'] = $page_size;
        $list['total_num'] = $total_num;
        $list['data'] = $data;

        return $list;
    }
}